package com.kuang.order.service;

import com.kuang.bascic.service.BaseServiceImpl;
import com.kuang.bascic.utils.CodeGenerateUtils;
import com.kuang.bascic.utils.LoginContext;
import com.kuang.order.constant.OrderConstants;
import com.kuang.order.domain.OrderAddress;
import com.kuang.order.domain.OrderAdopt;
import com.kuang.order.domain.Paybill;
import com.kuang.order.mapper.OrderAddressMapper;
import com.kuang.order.mapper.OrderAdoptMapper;
import com.kuang.order.mapper.PaybillMapper;
import com.kuang.pay.domian.AlipayInfo;
import com.kuang.pay.service.IpayService;
import com.kuang.pet.domain.Pet;
import com.kuang.pet.mapper.PetMapper;
import com.kuang.quartaz.job.CancelOrder;
import com.kuang.quartaz.utils.QuartzJobInfo;
import com.kuang.quartaz.utils.QuartzUtils;
import com.kuang.user.domian.User;
import com.kuang.user.domian.UserAddress;
import com.kuang.user.mapper.UserAddressMapper;
import org.quartz.JobDataMap;
import org.quartz.Scheduler;
import org.quartz.SchedulerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.Date;
import java.util.Map;

@Service
public class OrderAdoptServiceImpl extends BaseServiceImpl<OrderAdopt> implements OrderAdoptService {
//    @Autowired
//    private OrderAdoptMapper orderAdoptMapper;
    @Autowired
    private PetMapper petMapper;
    @Autowired
    private OrderAdoptMapper orderAdoptMapper;
    @Autowired
    private UserAddressMapper userAddressMapper;
    @Autowired
    private OrderAddressMapper orderAddressMapper;
    @Autowired
    private PaybillMapper paybillMapper;
    @Autowired
    private IpayService ipayService;
    @Autowired
    private SchedulerFactoryBean schedulerFactoryBean;
    @Override
    @Transactional
    public String createOrder(Map<String, String> map, HttpServletRequest req) {
        // 获取到接受的信息
        String adress = map.get("adress");
        String payaway = map.get("payaway");
        // 宠物id
        String petId = map.get("petId");
        // 获取当前的用户
        User user = (User) LoginContext.getCurrenUser(req);
        // 修改状态为下架
        Pet pet = petMapper.selectDepartmentById(Long.valueOf(petId));
        // 修改状态为已售出 2 为已售出
        pet.setState(2);
        // 设置认购主人
        pet.setUser_id(user.getId());
        petMapper.UpdateDepartment(pet);
        // 根据传过来的宠物id 封装成为一个OrderAdope对象
        OrderAdopt orderAdopt = petIdToOrderAdope(pet, user);
        orderAdopt.setAddress_id(Long.valueOf(adress));
        //新增一个宠物领养订单
        orderAdoptMapper.addAdopt(orderAdopt);
        //根据传过来的地址id 查询user_address ，生成一个orderAddress
        UserAddress userAddress = userAddressMapper.selectDepartmentById(Long.valueOf(adress));
        OrderAddress orderAddress = userAddressToorderAddress(userAddress);
        //填充不能copy的字段
        orderAddress.setOrderSn(orderAdopt.getOrderSn());
        // 返回获取主键id
        orderAddress.setOrder_id(orderAdopt.getId());
        //新政订单地址
        orderAddressMapper.addDepartment(orderAddress);
        // 把订单设为一个支付单  多总订单系统合并为一个
        Paybill paybill = orderAdoptTot_pay_bill(orderAdopt);
        //设置支付类型
        paybill.setBusinessType(OrderConstants.ORDER_ADOPT);
        //设置业务主键也就是领养id  通过id查询最快
        paybill.setBusinessKey(orderAdopt.getId());
        //设置支付方式
        paybill.setPayChannel(payaway);
        //添加到paybill表中
        paybillMapper.addDepartment(paybill);
        // 去支付  封装业务层 可以多种支付方式使用
        //先查询  为了防止二次清算理应下单店铺id去获取店铺的密钥等等  现在直接就一个就直接使用id1
        AlipayInfo alipayInfo = ipayService.selectDepartmentById(1L);
        String pay = ipayService.pay(paybill,alipayInfo);
        // 这个结果的市html页面 意思拉起收银台 js绑定的第一个元素直接提交跳转地址
//        <form name="punchout_form" method="post" action="https://openapi.alipaydev.com/gateway.do?charset=utf-8&method=alipay.trade.page.pay&sign=boBOGGp6%2F9GEwgXPV%2BZhxRrNJiyv8BpjRf3LnQMp%2BGLAbIlSEu3Y5KfwX0FDj7%2BNm39V8Jt0%2FLTCttZG1xAoMoiLna3q5JNgOBy1RA98g6VCDbZ18dp13mQr%2BSx8qtob3wFok6OYiuQX%2F9j8GFIZL%2FNhRQnd4%2BE8ywf6hexFncFzazlznyyiadLMXeZkBtXqjrp09X8PpD28Jnz1OdOO6tF1565Ph9YeEI1Kg7i4RN4HcilxYNjaGNa5T6xjQAQ9v9vavBlorc7q2gaLyf1XdIs1X0RhDhUN0SO%2BDkqghfzk5WddMIdr1%2B5KY%2Brv1ELbPdwKvPgvIH76Gx7fCZmczA%3D%3D&return_url=http%3A%2F%2F3tb7ab.natappfree.cc%2Fpay%2Freturn_url&notify_url=http%3A%2F%2F3tb7ab.natappfree.cc%2Fpay%2Fnotify_url&version=1.0&app_id=2016082100302609&sign_type=RSA2&timestamp=2022-07-12+11%3A01%3A43&alipay_sdk=alipay-sdk-java-3.4.27.ALL&format=json">
//<input type="hidden" name="biz_content" value="{&quot;out_trade_no&quot;:&quot;1420861562&quot;,&quot;total_amount&quot;:&quot;1.00&quot;,&quot;subject&quot;:&quot;[宠物之家-购物订单]&quot;,&quot;body&quot;:&quot;[宠物之家-购物订单]&quot;,&quot;product_code&quot;:&quot;FAST_INSTANT_TRADE_PAY&quot;}">
//<input type="submit" value="立即支付" style="display:none" >
//</form>
//<script>document.forms[0].submit();</script>
        // 设置定时任务 lasttime时间过了之后修改订单
        //获取schduler
        Scheduler scheduler = schedulerFactoryBean.getScheduler();
        JobDataMap jobDataMap = new JobDataMap();
        jobDataMap.put("orderSn",paybill.getOrderSn());
        Date lastPayTime = paybill.getLastPayTime();
        QuartzJobInfo quartzJobInfo = new QuartzJobInfo();
        // 定时器
        String corn = quartzJobInfo.setFireDate(lastPayTime);
        //设置定时任务
        // job名字必须唯一 所以这里名字取名系统订单号
        QuartzUtils.addJob(scheduler,paybill.getOrderSn(), CancelOrder.class,jobDataMap,corn);
        return pay;

    }

    private Paybill orderAdoptTot_pay_bill(OrderAdopt orderAdopt) {
        Paybill paybill = new Paybill();
        BeanUtils.copyProperties(orderAdopt,paybill);
        paybill.setMoney(orderAdopt.getPrice());

        return paybill;

    }

    private OrderAddress userAddressToorderAddress(UserAddress userAddress) {
        OrderAddress orderAddress = new OrderAddress();
        BeanUtils.copyProperties(userAddress,orderAddress);
        return orderAddress;
    }

    private OrderAdopt petIdToOrderAdope(Pet pet, User user) {
        OrderAdopt orderAdopt = new OrderAdopt();
//        private String paySn; 渠道
//        private String digest; 摘要
        orderAdopt.setDigest("[宠物之家-购物订单]");
//        private Long pet_id;宠物id
        orderAdopt.setPet_id(pet.getId());
//        private BigDecimal price;宠物价格
        orderAdopt.setPrice(pet.getSaleprice());
//        private Date lastConfirmTime; 最后确认时间 当前时间加上15分钟
//        // 订单状态  0待支付  1已支付  2待确认（配送） -1 取消 -2退款
        orderAdopt.setState(0);
//        private String lastPayTime; // 在当前的基础上 往后延时15分钟
        orderAdopt.setLastPayTime(new Date(System.currentTimeMillis()+1000*60*1));
//        private String orderSn; // 订单编号（唯一不重复，全是数字）使用工具类 用户id传入 实现不重复
        String sn = CodeGenerateUtils.generateOrderSn(user.getId());
        orderAdopt.setOrderSn(sn);
//        private Long user_id; 领养人
        orderAdopt.setUser_id(user.getId());
//        private Long shop_id;店铺名
        orderAdopt.setShop_id(pet.getShop_id());
//        private Integer service_method;
        // 地址id
        return orderAdopt;

    }
}
